import json

import util


def load(query: str, size: int) -> list[dict]:
    logs = util.search_es(host="http:/localhost:9200", index_name="logs_index", match_fields={'logger': 'S_LINK'},
                          query_string=query,
                          size=size)
    result = []
    if not logs:
        return

    # 根据logs遍历构建结果
    for log in logs:
        message = log.get('message')
        cost = None
        req_id = None
        link = None
        if '[P]' in message:
            profiler_str = message.split('[P]')[1].strip()
            link = profiler_str
            segments = profiler_str.split(',')
            if len(segments) > 5:
                cost = segments[4].strip().split(')')[0]  # 第5个（0-based index是4）

            req_id = profiler_str.split('_req_id|')[1].split(';')[0].strip()
        elif '[L]' in message:
            link = json.loads(message.split('[L]')[1].strip())
            cost = link.get('cost')
            if link.get('digests'):
                for item in link.get('digests'):
                    if item['k'] == '_req_id':
                        req_id = item['v']
        else:
            continue
        result.append({
            'input': None,
            'cost': cost,
            'req_id': req_id,
            'link': link
        })

    return result


def detail( group: str, biz: str, action: str
           , req_id: str, link_id: str, success: str, status: str) -> dict:

    matchs = {
        'logger': 'S_DIGEST'
    }

    if '@' in req_id:
        matchs['traceid'] = req_id.split('@')[0]
        matchs['rpcid'] = req_id.split('@')[1]
    else:
        matchs['traceid'] = req_id

    logs = util.search_es(host="http:/localhost:9200", index_name="logs_index",match_fields=matchs, query_string='"'+link_id+'"',
                          size=1)
    if not logs:
        return {
        }
    else:
        return logs[0]



if __name__ == '__main__':
    xx = load(False,'JLg8StRXI2pAhuia',20)
    print(json.dumps(xx,ensure_ascii=False))